package org.example.api;

import org.example.dao.ArticleDao;
import org.example.model.Article;
import org.example.model.User;
import org.example.util.WebUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/blog/add")
public class BlogAddServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求数据：json格式通过request输入流来反序列化为Article对象
        Article a = WebUtil.deserialize(req, Article.class);
        //以上文章对象，包含请求传入的标题和内容，插入文章还需要user_id字段
        //获取session中的用户信息
        User user = WebUtil.validateLogin(req);
        if (user == null) {
            //没有登录，返回401
            resp.setStatus(401);
            return;
        }
        //登录，插入文章操作
        a.setUserId(user.getId());
        int n = ArticleDao.insert(a);
        Map<String, Object> map = new HashMap<>();
        map.put("ok", true);
        WebUtil.serialize(resp, map);
    }
}
